package com.silverhaze.diamond.server.util;

import com.silverhaze.commons.utils.NumberUtils;
import com.silverhaze.diamond.common.entity.Property;
import com.silverhaze.diamond.common.entity.Service;

import javax.persistence.EntityManager;

/**
 * This code is part of Kg.Axion project. Treat it as strictly confidential.
 * Created by Ivan Babanin.
 * Creation date: 02.10.11 2:57
 */
public class ServiceTrigger extends Trigger<Service> {
    @Override
    public void prePersist(Service value, EntityManager entityManager) {
        Object result = entityManager.createQuery("SELECT p.val FROM Property AS p WHERE p.key = :key").
                setParameter("key", Property.ORDER_ID_PROPERTY).getSingleResult();

        Long lastId = NumberUtils.getLong(result, null);

        if(lastId != null){
            value.setOrderId(lastId + 1);
        }
    }

    @Override
    public void postPersist(Service value, EntityManager entityManager) {
        entityManager.createQuery("UPDATE Property p SET p.val = :val WHERE p.key = :key").
                setParameter("key", Property.ORDER_ID_PROPERTY).setParameter("val", "" + value.getOrderId()).executeUpdate();
    }
}
